// pages/indexFhm1/indexFhm1.js
var app = getApp()
//常量数据配置
var ConstantData = require('../../../common/constant_data.js')
var common = require("../../../common/common.js")

Page({

  /**
   * 页面的初始数据
   */
  data: {
    payStatus:true,
    pageName: 'no_pay_tip',
    isSubOffical: true,
    officalSubImg: ConstantData.CONSTATNT_DATA.OFFICAL_SUB_IMG_URL,
  },

    /**
   * 跳转到关注公众号的页面
   */
  goFollowMp: function() {
    app.goFollowMp(-200007, '关注公众号-租金未支付')
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      isSubOffical: app.globalData.isSubOffical
    })
    // 记录展示关注公众号日志
    if (!app.globalData.isSubOffical) {
      app.recordShowMpLog(-200007, '关注公众号-租金未支付')
    }

    getApp().hideLoading(); 
    console.log('options',options)

    let isJson = common.isJSON(options.rentInfo);
    if(!isJson) {      
       common.recordErrorInfo(ConstantData.err_type.errResJson, "非json:no_pay_tip:options:" + JSON.stringify(options));          
       return;
    }       
    let rentInfo = JSON.parse(options.rentInfo);
    
    console.log('rentInfo',rentInfo);
    let windowHeight = wx.getStorageSync('systeminfo').windowHeight
    // let orderList = [{ openTime: '2019-09-12 12:00:00', backTime: '2019-09-12 12:00:00', leaseTimeLen: '1小时25分钟' }, { openTime: '2019-09-12 12:00:00', backTime: '2019-09-12 12:00:00', leaseTimeLen: '1小时25分钟' }];
    this.setData({
      borrowTime: rentInfo.borrowTime.replace(".0", ""),
      backTime: rentInfo.backTime.replace(".0", ""),
      costTime: rentInfo.costTime,
      rent: rentInfo.rent,
      equId: rentInfo.equId!=undefined ? rentInfo.equId: 0,
      orderCode: rentInfo.orderCode,
      orderType:rentInfo.orderType,
      deposit: rentInfo.deposit,
      totalTimeLenStr: rentInfo.inCycleLeaseTimeLen,
      orderList: rentInfo.inCycleRecordInfoList,
      windowHeight: windowHeight,
      noPayTitle:rentInfo.noPayTitle,
      priceLabel:rentInfo.priceLabel,
      noPayDepositTip: rentInfo.noPayDepositTip
    })
    this.data.isAutoRefund = rentInfo.depositBackSuc;
    this.data.backSucVoiceUrl = rentInfo.backSucVoiceUrl;
    let noBackRes = wx.getStorageSync('user_no_back');
    if (this.data.equId == 90777 && noBackRes && noBackRes.data.noBack.hid){
      this.setData({
        equId: noBackRes.data.noBack.hid
      })
    }
    let pages = getCurrentPages()
    let currPage = null //当前页面
    let prevPage = null //上一个页面
    currPage = pages[pages.length - 1] //当前页面
    prevPage = pages[pages.length - 2] //上一个页面
    if (prevPage && (prevPage.data.pageName == 'index' || prevPage.data.pageName == 'no_back_tip')) {
      app.globalData.userStay = true
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    getApp().hideLoading(); 
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    getApp().hideLoading(); 
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  toPayLease: function (event) {
    var extdata = event.currentTarget.dataset.extdata;    
    var orderCode = event.currentTarget.dataset.ordercode
    this.toPay(orderCode)
  },
  toPay: function (orderCode) {
    var that = this
    if (that.data.payStatus) {
    } else {
      console.log("支付中。。。。");
      wx.showToast({
        title: '支付中...',
      })
      return
    }
    that.setData({
      payStatus: false
    })
    console.log("去支付。。。" + orderCode)
    wx.showLoading({
      title: '处理中...',
    })
    app.executeRequest(function (header) {

      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/ejiam/wxmini/unpay/payment',
        method: 'post',
        header: header,
        data: {
          ordernum: orderCode
        },
        success: function (res) {
          var data = res.data
          console.log("支付结果---" + data.result)
          if (data.result == 0) {
            wx.showToast({
              title: '支付成功',
            })
            setTimeout(()=>{
              wx.redirectTo({
                url: '../lease_tip/lease_tip?pt=back&equId=' + that.data.equId + "&rent=" + that.data.rent + "&backtime=" + that.data.backTime + "&opentime=" + that.data.borrowTime + "&costtime=" + that.data.costTime
                + "&depositBackSuc=" + that.data.isAutoRefund + "&backSucVoiceUrl=" + that.data.backSucVoiceUrl + "&isVoice=true" ,
              })
            },1500)
          } else if (data.result == -1) {
            console.log("开始微信支付")
            that.toPayOrder(orderCode)
          } else {
            that.setData({
              alertBoxStatus: true,
              msg: data.description
            })
            getApp().hideLoading();
          }

        },
        complete: function (res) {
          console.log("恢复支付")
          that.setData({
            payStatus: true
          })
        }
      })

    })

  },
  toPayOrder: function (orderCode) {
    var that = this
    console.log("去支付。。。" + orderCode)
    app.toPayValideLogin(orderCode, function(loginCode, orderCode, err){
    
      app.executeRequest(function (header) {

        wx.request({
          url: ConstantData.CONSTATNT_DATA.BASE_URL + '/ejiam/wxmini/weixin/pay',
          method: 'post',
          header: header,
          data: {
            orderCode: orderCode,
            loginCode: loginCode,
            wxErr: err
          },
          success: function (res) {
            getApp().hideLoading();
            var data = res.data
            console.log("支付结果---" + data.result)
            if (data.result != 0 || !data.data || !data.data.timeStamp) {
              //已支付成功
              let paiedStat = 4;
              if(data.result == paiedStat) {
                wx.redirectTo({
                  url: '../lease_tip/lease_tip?pt=back&equId=' + that.data.equId + "&rent=" + that.data.rent + "&backtime=" + that.data.backTime + "&opentime=" + that.data.borrowTime + "&costtime=" + that.data.costTime
                  + "&depositBackSuc=" + that.data.isAutoRefund + "&backSucVoiceUrl=" + that.data.backSucVoiceUrl + "&isVoice=true",
                })
                return;
              }
              console.log("租金支付失败----result=" + data.result + ",description=" + data.description)
              that.setData({
                msg: data.description ? data.description:'支付失败',
                alertBoxStatus: true
              })
              return
            }
            wx.requestPayment({
              appId: 'wx0e458dc331e557cc',
              timeStamp: data.data.timeStamp,
              nonceStr: data.data.nonceStr,
              package: data.data.package,
              signType: data.data.signType,
              paySign: data.data.paySign,
              success: function (res) {
                console.log("SUCCESS")
                console.log(res);
                that.setData({
                  pageNum: 1,  //每次触发上拉事件，把searchPageNum+1  
                  leseList: []
                });
                // if (wx.requestSubscribeMessage) {
                //   wx.requestSubscribeMessage({
                //     tmplIds: ['KnUsFuS2NB07Pf9xbznQlyK_qZOU7DxOFl8l6E26Nww', '-S91jtVpX2Vto5EyXauKW008LYSSbsZiI8IWdepDarE'],
                //     success(res) {
                //       wx.request({
                //         url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease_user/wx_sub_msg',
                //         header: header
                //       })}
                //   })
                // } 
                wx.redirectTo({
                  url: '../lease_tip/lease_tip?pt=back&equId=' + that.data.equId + "&rent=" + that.data.rent + "&backtime=" + that.data.backTime + "&opentime=" + that.data.borrowTime + "&costtime=" + that.data.costTime 
                  + "&depositBackSuc=" + that.data.isAutoRefund + "&backSucVoiceUrl=" + that.data.backSucVoiceUrl + "&isVoice=true",
                })
              },
              fail: function (res) {
                common.recordErrorInfo(ConstantData.err_type.pay_fail, res ? JSON.stringify(res) : '');
              },
              complete: function (res) {
                console.log("complete--" + data.data.paySign)
                console.log(res)
              }
            })
          },
          complete: function (res) {
            console.log("恢复支付。。。")
            that.setData({
              payStatus: true
            })
          }
        })
  
      })
      
    });
  

  },
  alertBoxBtnClick: function(){
    this.setData({
      alertBoxStatus: false
    })
  }

})